from peewee import (
    SqliteDatabase, CharField, IntegerField, DateTimeField, Model, AutoField
)
import pandas as pd

db = SqliteDatabase('demo.db')


class DemoTable(Model):

    # 示例字段1
    field1 = CharField()

    # 示例字段2
    field2 = IntegerField()

    # 示例字段3
    field3 = DateTimeField()

    class Meta:
        database = db
        table_name = 'demo_table'

    @classmethod
    def insert_one_record(cls, **kwargs):
        try:
            cls.create(**kwargs)

            return {
                'status': 'success'
            }
        except Exception as e:
            return {
                'status': 'error',
                'message': str(e)
            }

    @classmethod
    def delete_one_record(cls, id):
        try:
            cls.delete().where(cls.id == id).execute()

            return {
                'status': 'success'
            }
        except Exception as e:
            return {
                'status': 'error',
                'message': str(e)
            }

    @classmethod
    def alter_one_record(cls, id, **kwargs):
        try:
            cls.update(**kwargs).where(cls.id == id).execute()

            return {
                'status': 'success'
            }
        except Exception as e:
            return {
                'status': 'error',
                'message': str(e)
            }


db.create_tables([DemoTable])

# 生成测试数据用于演示
if DemoTable.select().count() == 0:
    for i in range(1, 101):
        DemoTable.insert_one_record(
            field1='测试数据{}'.format(i),
            field2=i,
            field3='2020-01-01 00:00:00'
        )
